package org.example.system.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.config.RequestWrapper;
import org.example.system.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问此拦截器前，token验证已通过
 * 在访问接口之前拦截，判断用户权限是否满足要求
 */
@Component
@Slf4j
public class RoleInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer","").trim();
        String payload = JwtUtil.get(token);
        Long id = Long.parseLong(payload.split(",") [0]); //通过token获取用户id
        //查询用户权限
        String role = userService.getOne(id).getRole();
        log.info("--------------RoleInterceptor | preHandle | role：{}",role);
        if (role.equals("ADMIN")){//如果是管理员访问所有接口放行
            return true;
        }
        String result = JSON.toJSONString(R.fail(403,"身份权限不足"));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(result);
        response.getWriter().flush();
        return false;
    }
}
